import React, { useState, useEffect, useRef } from 'react';
import { Row, Col, Select } from 'antd';
import LineStackChart from 'src/components/Chart/LineStackChart';
import FilterTool from 'src/components/FilterTool';
import '../../../StrategyLabs/Detail/index.less';
import services from 'src/services/api';
import { round } from 'src/utils/utils';
import { tooltipFormatter } from '../utils';
import moment from 'moment';
import { getCodeByKey } from 'src/utils/utils';

export default function ApisMonitor(props) {
  const [featureApi, setFeatureApi] = useState([]); // 指标
  const [deviceApi, setDeviceApi] = useState([]); // 设备
  const [riskApi, setRiskApi] = useState({}); // 风险识别
  const [modelApi, setModelApi] = useState({}); // 模型api
  const [modelList, setModelList] = useState([]); // 模型namelist
  const [currentModelId, setCurrentModelId] = useState(''); // 模型namelist
  const filterParams = useRef({});

  const isOnlyModel =
    props.match.params.id !== undefined
      ? true
      : getCodeByKey(props.location.search, 'onlyModel') === 'true'
      ? true
      : false; // 是否只展示model
  console.log(isOnlyModel);
  useEffect(() => {
    getModel();
  }, []);

  function getModelApi(model_id) {
    setCurrentModelId(model_id);
    apiMonitor({ ...filterParams.current, type: 'model', extra: { service_id: model_id } });
  }
  const filterItems = [
    {
      type: 'rangepicker',
      key: 'start',
      name: ['start', 'end'],
      label: '统计时间',
      defaultValue: [
        moment()
          .subtract(6, 'day')
          .startOf('day')
          .format('YYYY-MM-DD HH:mm'),
        moment().format('YYYY-MM-DD HH:mm'),
      ],
      disabledDate: (current) => {
        return (
          current &&
          (current > moment().endOf('day') ||
            current <
              moment()
                .subtract(30, 'day')
                .endOf('day'))
        );
      },
      ranges: {
        本周: [moment().startOf('week'), moment()],
        近7天: [moment().subtract('days', 6), moment()],
        本月: [moment().startOf('month'), moment()],
        近30天: [moment().subtract('days', 29), moment()],
      },
      format: 'YYYY-MM-DD HH:mm',
      placeholder: ['起始时间', '结束时间'],
      allowClear: false,
    },
  ];

  function getStatistics(params, type = true) {
    if (!type) return;
    filterParams.current = params;
    apiMonitor({ ...params, type: 'risk' });
    apiMonitor({ ...params, type: 'device' });
    apiMonitor({ ...params, type: 'feature' });

    if (currentModelId !== '') {
      apiMonitor({ ...params, type: 'model', extra: { service_id: currentModelId } });
    }
  }

  function apiMonitor(params) {
    services.devOpt.apiMonitor(params).then((res) => {
      if (res.code === 0) {
        switch (params.type) {
          case 'risk':
            setRiskApi(res.data);
            break;
          case 'device':
            setDeviceApi(res.data);
            break;
          case 'feature':
            setFeatureApi(res.data);
            break;
          case 'model':
            setModelApi(res.data);
            break;
          default:
            break;
        }
      }
    });
  }

  // 请求模型
  function getModel() {
    services.model.nameList({ service_status: 2 }).then((res) => {
      if (res.code === 0) {
        setModelList(res.data);
        const service_id =
          props.match.params.id !== undefined
            ? Number(props.match.params.id)
            : Number(getCodeByKey(props.location.search, 'service_id'));
        getModelApi(service_id ? service_id : res.data[0].service_id);
      }
    });
  }
  const yAxis = featureApi.reduce((arr, it) => {
    if (!arr.find((item) => item.name === it.unit)) {
      const c =
        arr.length >= 1
          ? {
              key: it.unit,
              type: 'value',
              nameLocation: 'start',
              minInterval: 1,
              axisLabel: {
                formatter: it.unit === 'ms' ? '{value} ms' : '{value}',
              },
            }
          : {
              key: it.unit,
              type: 'value',
              minInterval: 1,
              axisLabel: {
                formatter: it.unit === 'ms' ? '{value} ms' : '{value}',
              },
            };
      arr.push(c);
    }
    return arr;
  }, []);

  // echart 指标响应tooltip的formatter
  function featureTooltipFormatter(params) {
    const p = params.reduce((values, it) => {
      const unit = it.seriesName.indexOf('响应') !== -1 ? 'ms' : '次';
      const current_value = `${it.marker}${it.seriesName}: ${round(it.value, 0)}${unit}`;
      return values === '' ? current_value : `${values}<br/>${current_value}`;
    }, '');
    return `${params[0].name}<br/>${p}`;
  }
  return (
    <div className='detail-page'>
      <FilterTool
        data={filterItems}
        colNum={4}
        query={getStatistics}
        refreshFilter={getStatistics}
        isOnChange={true}
        justify='start'
      />
      <Row style={{ marginTop: '20px' }}>
        {!isOnlyModel && (
          <>
            <Col span={24} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>引擎识别接口</h4>
                </div>
                <div className='chart-box'>
                  <Row span={20}>
                    <Col span={12}>
                      <h5>执行响应情况</h5>
                      <LineStackChart
                        id='riskApi.response'
                        width='100%'
                        height='300px'
                        dataSource={riskApi.response || []}
                        xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                        yAxis={[
                          {
                            type: 'value',
                            name: '执行次数(次)',
                            key: '执行次数',
                            minInterval: 1,
                          },
                          {
                            key: '响应时间',
                            type: 'value',
                            name: '响应时间(ms)',
                            minInterval: 1,
                            position: 'right',
                          },
                        ]}
                        yAxisKey='name'
                        dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                        tooltipFormatter={featureTooltipFormatter}
                      />
                    </Col>
                    <Col span={12}>
                      <h5>调用错误趋势</h5>
                      <LineStackChart
                        id='riskApi.error_trend'
                        width='100%'
                        height='300px'
                        dataSource={riskApi.error_trend || []}
                        xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                        dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                        tooltipFormatter={(params) => {
                          return tooltipFormatter(params, 2);
                        }}
                      />
                    </Col>
                  </Row>
                </div>
              </div>
            </Col>
            <Col span={24} style={{ marginBottom: '20px' }}>
              <div className='risk-trend-box'>
                <div className='chart-head'>
                  <h4>设备指纹接口</h4>
                </div>
                <div className='chart-box'>
                  <Row span={20}>
                    <Col span={12}>
                      <h5>执行响应情况</h5>
                      <LineStackChart
                        id='deviceApi.response'
                        width='100%'
                        height='300px'
                        yAxis={[
                          {
                            type: 'value',
                            name: '执行次数(次)',
                            key: '执行次数',
                            minInterval: 1,
                          },
                          {
                            key: '响应时间',
                            type: 'value',
                            name: '响应时间(ms)',
                            minInterval: 1,
                          },
                        ]}
                        yAxisKey='name'
                        dataSource={deviceApi.response || []}
                        xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                        dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                        tooltipFormatter={featureTooltipFormatter}
                      />
                    </Col>
                    <Col span={12}>
                      <h5>调用错误趋势</h5>
                      <LineStackChart
                        id='deviceApi.error_trend'
                        width='100%'
                        height='300px'
                        dataSource={deviceApi.error_trend || []}
                        xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                        dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                        tooltipFormatter={(params) => {
                          return tooltipFormatter(params, 2);
                        }}
                      />
                    </Col>
                  </Row>
                </div>
              </div>
            </Col>
          </>
        )}
        <Col span={24} style={{ marginBottom: '20px' }}>
          <div className='risk-trend-box'>
            <div className='chart-head'>
              <h4>模型接口</h4>
              <Select value={currentModelId} onChange={(value) => getModelApi(value)}>
                {modelList.map((it) => (
                  <Select.Option value={it.service_id} key={it.service_id}>
                    {it.service_name}
                  </Select.Option>
                ))}
              </Select>
            </div>
            <div className='chart-box'>
              <Row span={20}>
                <Col span={12}>
                  <h5>执行响应情况</h5>
                  <LineStackChart
                    id='modelApi.response'
                    width='100%'
                    height='300px'
                    yAxis={[
                      {
                        type: 'value',
                        name: '执行次数(次)',
                        key: '执行次数',
                        minInterval: 1,
                      },
                      {
                        key: '响应时间',
                        type: 'value',
                        name: '响应时间(ms)',
                        minInterval: 1,
                      },
                    ]}
                    yAxisKey='name'
                    dataSource={modelApi.response || []}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    tooltipFormatter={featureTooltipFormatter}
                  />
                </Col>
                <Col span={12}>
                  <h5>调用错误趋势</h5>
                  <LineStackChart
                    id='modelApi.error_trend'
                    width='100%'
                    height='300px'
                    dataSource={modelApi.error_trend || []}
                    xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                    dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                    tooltipFormatter={(params) => {
                      return tooltipFormatter(params, 2);
                    }}
                  />
                </Col>
              </Row>
            </div>
          </div>
        </Col>
        {!isOnlyModel && (
          <Col span={24} style={{ marginBottom: '20px' }}>
            <div className='risk-trend-box'>
              <div className='chart-head'>
                <h4>指标接口</h4>
              </div>
              <div className='chart-box'>
                <h5>执行响应情况</h5>
                <LineStackChart
                  id='featureApi'
                  width='100%'
                  height='300px'
                  dataSource={featureApi}
                  xRender={(it) => moment(it[0] * 1000).format('YYYY-MM-DD HH:mm:ss')}
                  dataRender={(it) => (Number.isNaN(Number(it[1])) ? 0 : Number(it[1]))}
                  yAxis={yAxis}
                  yAxisKey='unit'
                  dataKey={'1'}
                  tooltipFormatter={featureTooltipFormatter}
                />
              </div>
            </div>
          </Col>
        )}
      </Row>
    </div>
  );
}
